import { createContext } from "solid-js";
import { TypePageFocus } from "../type";
import { keysOther } from "../path/key"
import { getKeyValue } from "../path/until";


export const getFocusContext: () => TypePageFocus.State = (() => {
  const _state: TypePageFocus.StateValue = {
    keys: keysOther,
    popupList: [],
    keyDownStore: {},
  }
  //数据中心配置
  const _option: TypePageFocus.StateOptions = {
    /**弹出层发生改变的事件 */
    popupChange(item: TypePageFocus.PopupItem) {
      const _idx = _state.popupList.findIndex(v => v.uid === item.uid)
      if (_idx > -1) {
        _state.popupList[_idx] = item
      } else {
        _state.popupList.push(item)
      }
    },
    triggerKeyDown: (ev: KeyboardEvent) => {
      const _keyValue = getKeyValue(ev.keyCode, _state.keys)
      if (!_keyValue) return
      for (const key in _state.keyDownStore) {
        if (Object.prototype.hasOwnProperty.call(_state.keyDownStore, key)) {
          const _fun = _state.keyDownStore[key];
          if (typeof _fun === "function") {
            _fun(_keyValue, ev)
          }
        }
      }
    },
    listenerKeyDown(id: string, fn: TypePageFocus.TypeKeyDownFn) {
      if (typeof fn !== "function") throw new Error("请传入回调函数")
      _state.keyDownStore[id] = fn
    },
    unListenerKeyDown(id: string) {
      delete _state.keyDownStore[id]
    },
  }
  return [_state, _option]
});

export const FocusContext = createContext<TypePageFocus.State>(getFocusContext());